package com.crl.manager
{
	import flash.events.TimerEvent;
	import flash.utils.Dictionary;
	import flash.utils.Timer;

	/**
	 * 心跳管理器; 
	 * @author crl
	 * 
	 */	
	public class TickManager implements ITickable
	{
		private var timer:Timer;
		
		private var  _delay:int;
		
		private var queue:Dictionary
		public function TickManager(delay:int=100,autoStart:Boolean=true)
		{
			if(delay<19){
				delay=19;
			}
			_delay=delay;
			timer=new Timer(delay);
			timer.addEventListener(TimerEvent.TIMER,timerHandler);
			
			if(autoStart){
				start();
			}
			
			queue=new Dictionary();
		}
		
		public function start():void{
			timer.start();
		}
		public function stop():void{
			timer.stop();
		}
		
		private function timerHandler(event:TimerEvent):void{
			tick(_delay);
		}
		
		public function add(value:ITickable):Boolean{
			if(queue[value]==null){
				queue[value]=1;	
				return true;
			}
			return false;
		}
		
		public function remove(value:ITickable):Boolean{
			if(queue[value]){
				queue[value]=null;
				delete queue[value];
				return true;
			}
			return false;
		}
		
		public function tick(time:int):void
		{
			for(var tickable:* in queue){
				tickable.tick(time);
			}
		}
	}
}